package com.njqy.ticket.util;

import com.njqy.ticket.dto.common.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CommonUtil {

    public static String getUserName() {
        String name = "";
        try{
            UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser)authentication.getPrincipal();
            name = loginUser.getUsername();
        }catch (Exception e){
            name = "";
        }
        return name;
    }

    public static String getTime() {
        DateTimeFormatter fmTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(fmTime);
        return time;
    }

    public static String getTime(String format) {
        DateTimeFormatter fmTime = DateTimeFormatter.ofPattern(format);
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(fmTime);
        return time;
    }

    public static String toStr(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    public static String toStr(Object obj, String str) {
        return obj == null ? str : obj.toString();
    }

}
